package com.longge.wechat.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;




public class ipUtil {

	public static String getIpAddr(HttpServletRequest request) {  
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    
	    String[] str = ip.split(","); 
	    if(str!=null && str.length>1){ 
	    ip = str[0]; 
	    } 
	    
	    return ip;  
	}  
	
	public static String getMACAddress(String ip){

	  String str = "";

	  String macAddress = "";

	  try {

		  Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
	
		  InputStreamReader ir = new InputStreamReader(p.getInputStream());
	
		  LineNumberReader input = new LineNumberReader(ir);
	
		  for (int i = 1; i < 100; i++) {
	
			  str = input.readLine();
		
			  if (str != null) {
		
				  if (str.indexOf("MAC Address") > 1) {
			
					  macAddress = str.substring(str.indexOf("MAC Address") + 14, str.length());
				
					  break;
			
				  }
		
			  }
	
		  }

	  } catch (IOException e) {

	  e.printStackTrace(System.out);

	  }

	  return macAddress;

	  }
	
	public static String getRemortIP(HttpServletRequest request) {  
	    if (request.getHeader("x-forwarded-for") == null) {  
	        return request.getRemoteAddr();  
	    }  
	    return request.getHeader("x-forwarded-for");  
	}  
	
	
	/**
	34
	     * @return 本机IP
	35
	     * @throws SocketException
	36
	     */
	
    public static String getRealIp() throws SocketException {

        String localip = null;// 本地IP，如果没有配置外网IP则返回它

        String netip = null;// 外网IP

        Enumeration<NetworkInterface> netInterfaces =

            NetworkInterface.getNetworkInterfaces();

        InetAddress ip = null;

        boolean finded = false;// 是否找到外网IP

        while (netInterfaces.hasMoreElements() && !finded) {

            NetworkInterface ni = netInterfaces.nextElement();

            Enumeration<InetAddress> address = ni.getInetAddresses();

            while (address.hasMoreElements()) {

                ip = address.nextElement();

                if (!ip.isSiteLocalAddress()

                        && !ip.isLoopbackAddress()

                        && ip.getHostAddress().indexOf(":") == -1) {// 外网IP

                    netip = ip.getHostAddress();

                    finded = true;

                    break;

                } else if (ip.isSiteLocalAddress()

                        && !ip.isLoopbackAddress()

                        && ip.getHostAddress().indexOf(":") == -1) {// 内网IP

                    localip = ip.getHostAddress();

                }

            }

        }

        if (netip != null && !"".equals(netip)) {

            return netip;

        } else {

            return localip;

        }

    }
    
    
    @SuppressWarnings("rawtypes")
	public static String getIpAddress(HttpServletRequest request)
    {
      String ip = null;
      Enumeration enu = request.getHeaderNames();
      while (enu.hasMoreElements()) {
        String name = (String)enu.nextElement();
        if (name.equalsIgnoreCase("X-Forwarded-For")) {
          ip = request.getHeader(name);
        }
        else if (name.equalsIgnoreCase("Proxy-Client-IP")) {
          ip = request.getHeader(name);
        }
        else if (name.equalsIgnoreCase("WL-Proxy-Client-IP")) {
          ip = request.getHeader(name);
        }

        if ((ip != null) && (ip.length() != 0))
          break;

      }

      if ((ip == null) || (ip.length() == 0))
        ip = request.getRemoteAddr();

      return ip;
    }
    
    /**        * 获取真实IP        * @param request        * @return        */ 
    public static String getRealIp(HttpServletRequest request){ 
     // 目前网上流行的所谓“取真实IP地址”的方法，都有bug，没有考虑到多层透明代理的情况。      多数代码类似：      
    //String IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]!=null&& HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] !=String.Empty)?HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]:HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    //事实上，上面的代码只试用与用户只使用了1层代理，如果用户有2层，3层HTTP_X_FORWARDED_FOR 的值是：“本机真实IP,1层代理IP,2层代理IP,.....” ，
    //如果这个时候你的数据中保存IP字段的长度很小（15个字节），数据库就报错了。
    //所以取“真正”IP地址的方式，还应该判断 “HTTP_X_FORWARDED_FOR” 中是否有“,”逗号，或者长度是否超长（超过15字节 xxx.xxx.xxx.xxx）。
    String result = request.getHeader("x-forwarded-for"); 
    if(result!=null&&result.trim().length()>0) {
    	//可能有代理      
    	if(result.indexOf(".")==-1){ 
    		//没有“.”肯定是非IPv4格式     
    		result = null;
    	} else {  
    		if(result.indexOf(",")!=-1){
		//有“,”，估计多个代理。取第一个不是内网的IP。    
 		result = result.trim().replace("'",""); 
		String[] temparyip = result.split(","); 
		for(int i=0;i<temparyip.length;i++){ 
			if(isIPAddress(temparyip[i])  && temparyip[i].substring(0,3)!="10."&& temparyip[i].substring(0,7)!="192.168"&& temparyip[i].substring(0,7)!="172.16."){
	   				return temparyip[i]; //找到不是内网的地址    
			}
	       		}
    		}else if(isIPAddress(result)) {
    			//代理即是IP格式      
    			return result;
    		}else{ 
    			result = null; 
    			//代理中的内容 非IP，取IP     
    		} 
    	} 
   } 
   if (result== null || result.trim().length()==0){ 
	   result = request.getHeader("Proxy-Client-IP"); 
   }
   if (result== null || result.trim().length()==0){ 
     result = request.getRemoteAddr(); 
   }
   	return result; 
     
   } 
    
     
     /**       * 判断是否是IP地址格式       * @param str1       * @return       */ 
     public static boolean isIPAddress(String str1) { 
	     if(str1==null||str1.trim().length()<7||str1.trim().length()>15){ 
	     	return false;
	     }else {
	    	return true;
	    }
	 }
     
     
     
     public static String getWebIp() {
 		try {
 			String strUrl = "http://www.baidu.com";
 			URL url = new URL(strUrl);

 			BufferedReader br = new BufferedReader(new InputStreamReader(url

 			.openStream()));

 			String s = "";

 			StringBuffer sb = new StringBuffer("");

 			String webContent = "";

 			while ((s = br.readLine()) != null) {
 				sb.append(s + "\r\n");

 			}

 			br.close();
 			webContent = sb.toString();
 			int start = webContent.indexOf("[") + 1;
 			int end = webContent.indexOf("]");
 			webContent = webContent.substring(start, end);

 			return webContent;

 		} catch (Exception e) {
 			e.printStackTrace();
 			return "error open url:" + null;

 		}
 	}
     
     /**
      * 获取真实IP:
      *    先取
      * @param request
      * @return
      */
     public static String getClientIP(HttpServletRequest request) {
         String ip = request.getHeader("X-Real-IP");
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
             ip = request.getHeader("X-Forwarded-For");
         }
         if (ip == null || ip.length() == 0|| "unknown".equalsIgnoreCase(ip)) {
             ip = request.getRemoteAddr();
         }

         return ip;
     }
     
     
     public static String getIpAdr(HttpServletRequest request) {
 		String ipAddress = "";
 		// ipAddress = this.getRequest().getRemoteAddr();
 		//HttpServletRequest res = ServletActionContext.getRequest();
 		ipAddress = request.getHeader("x-forwarded-for");
 		if (ipAddress == null || ipAddress.length() == 0
 				|| "unknown".equalsIgnoreCase(ipAddress)) {
 			ipAddress = request.getHeader("Proxy-Client-IP");
 		}
 		if (ipAddress == null || ipAddress.length() == 0
 				|| "unknown".equalsIgnoreCase(ipAddress)) {
 			ipAddress = request.getHeader("WL-Proxy-Client-IP");
 		}
 		if (ipAddress == null || ipAddress.length() == 0
 				|| "unknown".equalsIgnoreCase(ipAddress)) {
 			ipAddress = request.getRemoteAddr();
 			if (ipAddress.equals("127.0.0.1")) {
 				// 根据网卡取本机配置的IP
 				InetAddress inet = null;
 				try {
 					inet = InetAddress.getLocalHost();
 				} catch (UnknownHostException e) {
 					e.printStackTrace();
 				}
 				ipAddress = inet.getHostAddress();
 			}

 		}

 		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
 		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
 			if (ipAddress.indexOf(",") > 0) {
 				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
 			}
 		}
 		return ipAddress;
 	}
    	
    	
	public static void main(String[] args) {
		System.out.println(getMACAddress("192.168.1.101"));
	}
}
